package com.android.vgongyi.service;

import java.io.IOException;
import java.util.ArrayList;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;

import com.android.vgongyi.dao.BaseDAO;
import com.android.vgongyi.dao.CommonDAO;
import com.android.vgongyi.dao.ImageDAO;
import com.android.vgongyi.entity.ImageEntity;
import com.android.vgongyi.utils.FileUtil;

public class CleanDB {
	private static final int IMAGE_SIZE = 10; 
	private static final int COMMON_SIZE = 10;
	
	public static void clearImageDB(Context context) throws IOException{
		ArrayList<String> list= new ArrayList<String>();
		ContentResolver resolver = context.getContentResolver();
		Cursor cursor =  resolver.query(BaseDAO.URI_IMAGE, null, null, null, null);
		if(cursor.getCount() <= IMAGE_SIZE){
			cursor.moveToFirst();
			while(cursor.moveToNext()){
				list.add(cursor.getString(cursor.getColumnIndex("imagepath")));
			}
	    	cursor.close();
	    }else{
	    	cursor.moveToLast();
	    	int lastId = Integer.valueOf(cursor.getString(cursor.getColumnIndex("_id")));
	    	cursor.close();
	    	ImageDAO imageDAO = new ImageDAO(context);
	    	for(int i = lastId - IMAGE_SIZE + 1; i < lastId; i++){
	    			ArrayList<ImageEntity> imagelist = new ArrayList<ImageEntity>();
	    			imagelist=imageDAO.query(null, "_id =" +i, null, null);
	    			if(null!=imagelist&&imagelist.size()>0){
	    				list.add(imagelist.get(0).getImagepath());
	    			}
	    		}
	    		imageDAO.delete("_id <"+ (lastId - IMAGE_SIZE + 1), null);
	    	}
		FileUtil.cleanImage(list);
	}
	
	public static void clearCommonDB(Context context){
		CommonDAO commonDAO = new CommonDAO(context);
		commonDAO.delete(null, null);
//		ContentResolver resolver = context.getContentResolver();
//		Cursor cursor =  resolver.query(BaseDAO.URI_COMMON, null, null, null, null);
//		if(cursor.getCount() <= COMMON_SIZE)
//	    	cursor.close();
//	    else{
//	    		cursor.moveToLast();
//	    		int lastId = Integer.valueOf(cursor.getString(cursor.getColumnIndex("_id")));
//	    		int num = lastId - COMMON_SIZE + 1;
//	    		CommonDAO commonDAO = new CommonDAO(context);
//	    		cursor.close();
//	    		commonDAO.delete("_id <"+ num, null);
//	    	}
		
		
	}
}
